<template>
  <div class="user">
    <el-card class="box-card">
      <!-- 上边搜索框 -->
      <div class="search clearfix">
        <div class="grabble-box fl">
          <el-input placeholder="请输入内容" v-model="input3">
            <el-select
              v-model="select"
              slot="prepend"
              class="select-box"
              placeholder="搜索条件"
            >
              <el-option label="id" value="1"></el-option>
              <el-option label="姓名" value="2"></el-option>
              <el-option label="岗位" value="3"></el-option>
            </el-select>
            <el-button
              type="primary"
              slot="append"
              icon="el-icon-search"
            ></el-button>
          </el-input>
        </div>
        <div class="fr bnt">
          <el-button @click="exportExcel" type="warning">导出</el-button>
          <el-button type="primary" @click="onClose" icon="el-icon-plus"
            >添加</el-button
          >
        </div>
      </div>
      <!-- 下边角色列表 -->
      <div class="table">
        <el-table ref="table" :data="tableData" border>
          <el-table-column prop="id" label="ID" width="80"> </el-table-column>
          <el-table-column prop="created_at" label="登记时间">
          </el-table-column>
          <el-table-column prop="name" label="姓名" width="120">
          </el-table-column>
          <el-table-column prop="email" label="邮箱"> </el-table-column>

          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button type="success" plain>修改</el-button>
              <el-button type="warning" @click="DeleteUser(scope.row)" plain
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="page">
        <el-pagination
          :page-size="20"
          :pager-count="11"
          layout="prev, pager, next"
          :total="1000"
        >
        </el-pagination>
      </div>
    </el-card>

    <el-dialog
      :visible.sync="inheritAttrs"
      :modal-append-to-body="false"
      title="添加用户"
    >
      <el-form
        ref="addUser"
        :model="formData"
        :rules="rules"
        size="medium"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="name">
          <el-input
            v-model="formData.name"
            placeholder="请输入用户名"
            clearable
            :style="{ width: '100%' }"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="用户密码" prop="password">
          <el-input
            v-model="formData.password"
            placeholder="请输入用户密码"
            clearable
            :style="{ width: '100%' }"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="isPassword">
          <el-input
            v-model="formData.isPassword"
            placeholder="请再次输入密码"
            clearable
            :style="{ width: '100%' }"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input
            v-model="formData.email"
            placeholder="请输入邮箱"
            clearable
            :style="{ width: '100%' }"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="onClose">取消</el-button>
        <el-button type="primary" @click="handelConfirm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 导出表格

import FileSaver from "file-saver";
import XLSX from "xlsx";

export default {
  data() {
    return {
      tableData: null,
      input3: "",
      select: "",
      search: "",
      value1: true,
      inheritAttrs: false,
      formData: {
        name: undefined,
        password: undefined,
        isPassword: undefined,
        email: undefined,
      },
      rules: {
        name: [
          {
            required: true,
            message: "请输入用户名",
            trigger: "blur",
          },
          {
            pattern: /^[a-zA-Z0-9_-]{4,16}$/,
            message: "用户名格式不对",
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            message: "请输入用户密码",
            trigger: "blur",
          },
          {
            pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/,
            message: "密码格式不对",
            trigger: "blur",
          },
        ],
        isPassword: [
          {
            required: true,
            message: "请确认用户密码",
            trigger: "blur",
          },
          {
            pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/,
            message: "密码格式不对",
            trigger: "blur",
          },
          
        ],
        email: [
          {
            required: true,
            message: "请输入邮箱",
            trigger: "blur",
          },
          {
            pattern: /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
            message: "邮箱格式不对",
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    this.getUser();
  },
  methods: {
    handleEdit(index, row) {
      console.log(index, row);
    },
    handleDelete(index, row) {
      console.log(index, row);
    },

    onClose() {
      if (this.inheritAttrs == true) {
        this.inheritAttrs = false;
      } else {
        this.inheritAttrs = true;
      }
      console.log("关闭显示");
    },
    // 添加用户
    handelConfirm() {
      console.log("添加");

      this.$refs["addUser"].validate((valid) => {
        console.log("判断==>", valid);
        if (valid) {
          this.axios({
            method: "post",
            url: "/users",
            data: {
              name: this.formData.name,
              password: this.formData.password,
              email: this.formData.email,
            },
          })
            .then((res) => {
              if (res.data.meta.status == 201) {
                console.log("我进来了");
                this.inheritAttrs = false;
                this.$refs["addUser"].resetFields();
                this.getUser();
              }
            })
            .catch((err) => {
              console.log(err);
            });
        } else {
          console.log("验证失败！！！");
        }

        //  console.log("666");
      });
    },
    // 删除用户
    async DeleteUser(uese) {
      console.log(`users/:${uese.id}`);
      // const { data: res } = await this.$http.delete(`users/id:${uese.id}`);
      let determineTheData = await this.$confirm(
        "此操作将永久删除改用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);

      if (determineTheData !== "confirm") {
        this.$message.info("已经取消删除！");
      } else {
        this.axios({
          method: "delete",
          url: `users/:${uese.id}`,
          data: {
            id: uese.id,
          },
        })
          .then((res) => {
            if (res.data.meta.status == 200) {
              this.getUser();
              this.$message.success(res.data.meta.msg);
            }
            console.log(res);
          })
          .catch((err) => {
            console.log(err);
          });
      }
    },
    // 修改用户
    // 获取用户列表

    async getUser() {
      const { data: res } = await this.$http.get(`users`);

      if (res.meta.status == 200) {
        console.log("用户列表==>", res);
        this.tableData = res.data.users;
      }
      console.log(this.tableData);
    },
    // 导出数据

    exportExcel() {
      console.log(this.$refs.table.$el);
      var xlsxParam = { raw: true }; // 导出的内容只做解析，不进行格式转换(添加此行代码表格中的百分比就不会再导出的时候被转换成小数点)
      let wb = XLSX.utils.table_to_book(this.$refs.table.$el, xlsxParam);
      let wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array",
      });
      // 获取当前的时间戳，用来当文件名
      let time = "用户列表";
      try {
        FileSaver.saveAs(
          new Blob([wbout], { type: "application/octet-stream" }),
          `${time}.xlsx`
        ); //${time}是自己导出文件时的命名，随意
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }
      return wbout;
    },
  },
};
</script>

<style lang="less" scoped>
@import "../../assets/css/user.less";
</style>
